//
//  SportReportShareController.m
//  CoolTennisBall
//
//  Created by Coollang on 2017/7/17.
//  Copyright © 2017年 CoolLang. All rights reserved.
//

#import "SportReportShareController.h"
#import "PNChart.h"
#import "NewCurveLineChartView.h"
#import "CoollangTennisBall-Swift.h"
#import <UICountingLabel/UICountingLabel.h>
#import "SportDetailReportModel.h"
#import "SportDetailItemModel.h"
#import "UIImage+ImageFromView.h"

NSString * const kopenAppstoreRE = @"https://appsto.re/cn/Y4Vl9.i";

@interface SportReportShareController ()
@property (weak, nonatomic) IBOutlet UILabel *namelabel;
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;
@property (weak, nonatomic) IBOutlet UIImageView *locationImg;
@property (weak, nonatomic) IBOutlet UIImageView *headIconImg;
@property (weak, nonatomic) IBOutlet UIView *circleView;
@property (strong, nonatomic) PNCircleChart *pnCircleView;
@property (weak, nonatomic) IBOutlet UICountingLabel *pointLabel;
@property (weak, nonatomic) IBOutlet UILabel *scoreDescriptionLabel;
@property (weak, nonatomic) IBOutlet UICountingLabel *scoreUnitLabel;


@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *reportNameLabels;

@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *reportValueLabel;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *unitLabels;


// 曲线
@property (weak, nonatomic) IBOutlet UIView *lineChartSuperView;
@property (weak, nonatomic) IBOutlet NewCurveLineChartView *lineChartView;

@property (weak, nonatomic) IBOutlet UILabel *avgSpeedDesclabel;
@property (weak, nonatomic) IBOutlet UIView *forehandDotView;
@property (weak, nonatomic) IBOutlet UILabel *forehandLabel;
@property (weak, nonatomic) IBOutlet UIView *backhandDotView;
@property (weak, nonatomic) IBOutlet UILabel *backHandLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameBottomDsecLabel;


@property (strong,nonatomic)UIImage *screenShotImage;




@end

@implementation SportReportShareController {
     UserInforItem *_userInfoItem;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _userInfoItem = [User getLastUser].userInforItem;
    [self configureLocalization];
    [self updateUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication]setStatusBarHidden:true withAnimation:UIStatusBarAnimationFade];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.dismissBlock) {
        self.dismissBlock();
    }
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication]setStatusBarHidden:false withAnimation:UIStatusBarAnimationFade];
}

- (void)updateUI {
    [self.view layoutIfNeeded];
    [self configureReportVlaue];
    [self configureCircleView];
    [self configureLineChartView];
    
}

- (void)configureReportVlaue {
    
    for (NSInteger i = 0; i < self.detailReportModel.detailDesArray.count; i++) {
        SportDetailItemModel *model = self.detailReportModel.detailDesArray[i];
        UILabel *reportNameLabel = self.reportNameLabels[i];
        UILabel *reportUnitLabel = self.unitLabels[i];
        UILabel *valueLabel = self.reportValueLabel[i];
        reportNameLabel.text = model.title;
        reportUnitLabel.text = model.unit;
        valueLabel.text = model.value;
    }
}

- (void)configureLocalization {
    [self.headIconImg sd_setImageWithURL:[NSURL URLWithString:_userInfoItem.headIconPath] placeholderImage:[UIImage imageNamed:@"头像亚军"] options:SDWebImageRetryFailed|SDWebImageLowPriority];
    self.namelabel.text = _userInfoItem.name;
    self.locationLabel.text = _userInfoItem.location;
    
    if (_userInfoItem.location.length <= 0){
        self.locationImg.image = nil;
    }else{
        self.locationImg.image = [UIImage imageNamed:@"rank_location"];
    }
    
    self.backhandDotView.layer.cornerRadius = 3;
    self.forehandDotView.layer.cornerRadius = 3;
    
    self.forehandLabel.text = NSLocalizedString(@"Forehand", @"正手");
    self.backHandLabel.text = NSLocalizedString(@"Backhand", @"反手");
    self.avgSpeedDesclabel.text = NSLocalizedString(@"Avg Swing Speed", nil);
    self.scoreDescriptionLabel.text = NSLocalizedString(@"Motor Score", @"运动评分");
    self.scoreUnitLabel.text = NSLocalizedString(@"Report.Unit.Points", nil);
    
    self.nameBottomDsecLabel.text = [NSString stringWithFormat:@"一%@%@一",_userInfoItem.name,NSLocalizedString(@"'s tennis sport report", nil)];
    
}

// 配置得分
- (void)configureCircleView {
    if (self.pnCircleView != nil) {
        [self.pnCircleView removeFromSuperview];
    }
    self.pnCircleView = [[PNCircleChart alloc] initWithFrame:self.circleView.bounds total:@100 current:@(self.detailReportModel.totalScore) clockwise:YES shadow:YES shadowColor:[UIColor colorWithHex:0xf2f2f2]];
    self.pnCircleView.strokeColor = [UIColor colorWithHex:0xffd246];
    self.pnCircleView.duration = 0;
    self.pnCircleView.showProgressAni = NO;
    self.pnCircleView.strokeColorGradientMiddle = [UIColor colorWithHex:0xfa5d4c];
    self.pnCircleView.strokeColorGradientStart = [UIColor colorWithHex:0xf8296b];
    self.pnCircleView.lineWidth = @10;
    self.pnCircleView.countingLabel.hidden = YES;
    [self.circleView addSubview:self.pnCircleView];
    [self.pnCircleView strokeChart];
    
    self.pointLabel.format = @"%d";
    self.pointLabel.text = @(self.detailReportModel.totalScore).stringValue;
   // [self.pointLabel countFrom:0 to:self.detailReportModel.totalScore withDuration:1];
}

// 配置底部曲线
- (NSArray *)calculateLineChartXDataSource
{
    NSMutableArray *dataArr = @[].mutableCopy;
    
    NSInteger minutes = self.detailReportModel.effectiveSportTime;
    if (minutes < 10) {
        return dataArr;
    }
    NSInteger integerMinutes = (NSInteger)roundf(minutes/10.0)*10;
    for (NSInteger i = 0; i < 10; i++) {
        [dataArr addObject:[NSString stringWithFormat:@"%ld",(long)i * integerMinutes/10]];
    }
    return dataArr;
}

- (NSArray *)calculateLineChartYDataSource
{
  
    User *user = [User getLastUser];
    RLMResults *results = [user.sportRecordItems objectsWhere:@"dateTimeStamp == %lld",self.selectedDayTimeStamp];
    SportRecordItem *item = [results firstObject];
    if (item == nil) {
        return nil;
    }
    
    RLMResults * swingResults = [item.barChartItems sortedResultsUsingProperty:@"unixTimeStamp" ascending:YES];
    
    NSMutableArray *forehandSwingResults = [NSMutableArray array];
    NSMutableArray *backhandSwingResults = [NSMutableArray array];
    for (BarChartItem *item in swingResults) {
        if (item.handType == HandDirectionTypeForeward){
            [forehandSwingResults addObject:item];
        }else {
            [backhandSwingResults addObject:item];
        }
    }
    
    NSArray *Swingresults = @[forehandSwingResults,backhandSwingResults];
    
    NSMutableArray *arrM = [NSMutableArray array];
   
    for (NSArray *resultsItem in Swingresults) {
        
        NSArray * barItems = resultsItem;
        NSInteger count = barItems.count/10;
        NSInteger speedSum = 0;
        NSInteger index = 0;
        NSMutableArray *dataArr = @[].mutableCopy;
        
        for (BarChartItem *item in barItems) {
            speedSum += [item.maxSpeed integerValue];
            if (index%(count - 1) == 0 && index != 0) {
                NSInteger averageSpeed = speedSum/count;
                [dataArr addObject:@(averageSpeed)];
                speedSum = 0;
                if (dataArr.count == 10) {
                    break;
                }
            }
            index++;
        }
        NSMutableArray * newDataArr = @[].mutableCopy;
//        if ([dataArr firstObject] != nil) {
//            [newDataArr addObject:[dataArr firstObject]];
//        }
        [newDataArr addObjectsFromArray:dataArr];
        [arrM addObject:newDataArr];
    }
    
    return arrM.copy;
}
- (void)configureLineChartView {
    
    __weak typeof(self) weakSelf = self;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray * xAxisArr = [weakSelf calculateLineChartXDataSource];
        NSArray *dataArr = (xAxisArr.count > 0) ? [weakSelf calculateLineChartYDataSource]:@[];
        NSArray *foreHandDataArr = (dataArr.count == 0) ? @[]:dataArr.firstObject;
        NSArray *backHandDataArr = (dataArr.count == 0) ? @[]:dataArr.lastObject;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.lineChartView ConfigerTheme:kTennisBaseStyle];
            [weakSelf.lineChartView defaultSuitableSettingCompare:0 maxValue:200 setAxis:kAxisLeft labelCount:5 show:YES drawGridLinesEnabled:YES axisLineColor:[UIColor clearColor]];
            [weakSelf.lineChartView defaultSuitableSettingCompare:0 maxValue:200 setAxis:kAxisRight labelCount:5 show:NO drawGridLinesEnabled:NO axisLineColor:[UIColor clearColor]];
            
            CurveLineItem *lineItem =  [[CurveLineItem alloc] initWithLineWidth:2.0 color:kSelectedColor fullColor:[UIColor colorWithHex:0x20BF9D alpha:0.3] xValues:xAxisArr yValues:foreHandDataArr];
            
            CurveLineItem *otherLineItem =  [[CurveLineItem alloc] initWithLineWidth:2.0 color:[UIColor colorWithHex:0xF8C353] fullColor:[UIColor colorWithHex:0xF8C353 alpha:0.3] xValues:xAxisArr yValues:backHandDataArr];
            
            [weakSelf.lineChartView drawLineWithCurveLineItemArr:@[lineItem,otherLineItem] showAnimation:NO];
            if (xAxisArr.count > 0) {
                [weakSelf.lineChartView configuerXAxisValus:xAxisArr];
            }
            [weakSelf performSelector:@selector(shareWithType:) withObject:nil afterDelay:0.5];
        });
    });
    
}

#pragma mark - 分享的方法
- (void)shareWithType:(SSDKPlatformType)type {
    
    self.screenShotImage = [UIImage imageFromView:self.view];
    type = self.type;
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    NSString *title = [NSString stringWithFormat:@"%@%@  ",_userInfoItem.name,NSLocalizedString(@"'s tennis sport report", nil)];
    //因为qq空间分享比较特殊所以要判断一下
    if (type == SSDKPlatformSubTypeQZone) {
        //创建分享参数
        [shareParams SSDKSetupShareParamsByText:@"酷浪网球分享"
         
                                         images:self.screenShotImage //传入要分享的图片
         
                                            url:[NSURL URLWithString:kopenAppstoreRE]
         
                                          title:@"我今天的成绩哦"
         
                                           type:SSDKContentTypeText|SSDKContentTypeImage];
        
    }else if (type == SSDKPlatformTypeFacebook) {
        [shareParams SSDKSetupShareParamsByText:[title stringByAppendingString:kopenAppstoreRE]
         
                                         images:self.screenShotImage //传入要分享的图片
         
                                            url:[NSURL URLWithString:@"www.coollang.com"]
         
                                          title:@"My grades today!"
         
                                           type:SSDKContentTypeImage];
    }else {
        //创建分享参数
        [shareParams SSDKSetupShareParamsByText:@"智能网球分享"
         
                                         images:self.screenShotImage //传入要分享的图片
         
                                            url:[NSURL URLWithString:@"www.coollang.com"]
         
                                          title:@"我今天的成绩哦"
         
                                           type:SSDKContentTypeImage];
    }
    //进行分享
    [ShareSDK share: type //传入分享的平台类型
     
         parameters:shareParams
     
     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
         if (state == SSDKResponseStateSuccess) {
             [MBProgressHUD showSuccessHudInView:[UIApplication sharedApplication].keyWindow message:NSLocalizedString(@"Share Successfully", "") afterDelay:1.5];
         }
         if (self.dismissBlock) {
             self.dismissBlock();
             self.dismissBlock = nil;
         }
     }];
}

@end
